import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { getGigaSkuAndProductId, getProductPrice, gotoGigaProductPage } from '@/lib/giga';
import { cn, concurrentLimit, generateRandomId, getPageList } from '@/lib/utils';
import {
  ColumnDef,
  ColumnPinningState,
  PaginationState,
  Row,
  SortingState,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from '@tanstack/react-table';
import { ArrowUpDown, RefreshCcw, Trash2, LoaderCircle } from 'lucide-react';
import { GigaAvaliable, useAvaliableDB } from '../entrypoints/gigab2b.content/hook/useAvaliableDB';

import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from '@/components/ui/pagination';
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import useLocalStorage from '@/entrypoints/hook/useLocalStorage';
import { saveFile } from '@/lib/filesystem';
import { useGigaNotPersisStore } from '@/store/gigaNotPersist';
import { memo, useDeferredValue, useId } from 'react';
import { toast } from 'sonner';

export interface TableData {
  skuInfo: string;
  [x: string]: number | string;
}

function customReductionSortingFn(
  id: string,
): (rowA: Row<TableData>, rowB: Row<TableData>) => number {
  return (rowA: Row<TableData>, rowB: Row<TableData>) => {
    const rowAValue = rowA.getValue(id + '') as number;
    const rowBValue = rowB.getValue(id + '') as number;

    const isRowANaN = Number.isNaN(rowAValue);
    const isRowBNaN = Number.isNaN(rowBValue);

    if (isRowANaN && isRowBNaN) {
      return 0;
    }

    if (isRowANaN) {
      return -1;
    }

    if (isRowBNaN) {
      return 1;
    }

    return rowAValue - rowBValue;
  };
}

function toDateString(timeStamp: number) {
  return new Date(timeStamp).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
  });
}

export default function AvaliableCollect({
  className,
  categoryName,
  skuInfos,
  ...props
}: {
  className: string;
  categoryName: string;
  skuInfos: string[];
} & React.HTMLAttributes<HTMLDivElement>) {
  if (!categoryName) {
    return <div></div>;
  }
  const { addAvaliable, getAvaliable, clearAvaliable } = useAvaliableDB(categoryName);
  const dispatch = useGigaNotPersisStore((state) => state.dispatch);

  const [tableData, setTableData] = useState<TableData[]>([]);
  const [timeStampKey, setTimeStampKey] = useState<Set<number>>(new Set());
  const [isfreshing, setIsfreshing] = useState(false);
  const [avaliableImportCount, setAvaliableImportCount] = useState(0);
  const [avaliableImportTotal, setAvaliableImportTotal] = useState(0);
  const [isRefresh, setIsRefresh] = useState(false);
  const deferredTimeStampKey = useDeferredValue(timeStampKey);
  const deferredTableData = useDeferredValue(tableData);

  const refreshAvailableRender = useCallback(async () => {
    setIsRefresh(true);
    const gigaAvaliableList = await getAvaliable();
    gigaAvaliableList.sort((a, b) => {
      return a.skuInfo.localeCompare(b.skuInfo);
    });
    const avaliableList: TableData[] = [];
    const newTimeStampKeySet = new Set<number>();
    gigaAvaliableList.forEach((gigaAvaliable) => {
      const { skuInfo, avaliable, timeStamp } = gigaAvaliable;
      newTimeStampKeySet.add(timeStamp);
      const data = avaliableList.find((avaliable) => {
        return avaliable.skuInfo === skuInfo;
      });
      if (data) {
        data[timeStamp] = avaliable;
      } else {
        avaliableList.push({
          skuInfo,
          [timeStamp]: avaliable,
        });
      }
    });
    setTableData(avaliableList);
    setTimeStampKey(newTimeStampKeySet);
    setIsRefresh(false);
  }, [getAvaliable]);

  const runTask = useCallback(
    async (skuInfo: string, timeStamp: number) => {
      const [gigaSku, gigaProductId] = getGigaSkuAndProductId(skuInfo);
      let data = {} as Omit<GigaAvaliable, 'id'>;
      try {
        const result = await getProductPrice(gigaProductId);
        if (result.code === 200) {
          if (!result.data.qty_visible) {
            throw new Error('请先登录 giga 网站');
          }
          data = {
            skuInfo,
            timeStamp,
            // 对于非公开的产品,是没法获取库存数据的,这个时候把库存设置为 0
            avaliable: result.data?.quantity?.quantity || 0,
          };
          await addAvaliable(data);
        } else {
          throw new Error(`${result && result.msg}`);
        }
      } catch (error) {
        toast.error(`${skuInfo}: 获取库存失败 ${(error as Error).message}`, {
          position: 'top-right',
        });
        throw error;
      }
    },
    [addAvaliable],
  );

  async function fetchAvailable() {
    const timeStamp = Date.now();
    // const refreshAvailableRenderThrottle = throttle(refreshAvailableRender, 500);
    dispatch({
      type: 'update',
      update(draftState) {
        draftState.availableConcurrent.currentCategoryName = categoryName;
      },
    });
    await Promise.all(
      skuInfos.map((skuInfo) => {
        return new Promise((resolve, reject) => {
          dispatch({
            type: 'enqueueTask',
            resolve,
            reject,
            task: {
              handleTask: async () => {
                await runTask(skuInfo, timeStamp);
                // refreshAvailableRenderThrottle();
                refreshAvailableRender();
              },
              taskInfo: {
                id: skuInfo,
                skuIdInfo: skuInfo,
                categoryName: categoryName,
              },
            },
          });
        });
      }),
    );
    // 节流可能会导致末尾更新不会执行,因此最后还需要执行一次
    // refreshAvailableRender();
  }

  const fetchAvaliableBySkuInfo = useCallback(
    async (skuInfo: string, timeStamp = Date.now()) => {
      const [gigaSku, gigaProductId] = getGigaSkuAndProductId(skuInfo);
      let data = {} as Omit<GigaAvaliable, 'id'>;
      try {
        const result = await getProductPrice(gigaProductId);
        // console.log(result);
        data = {
          skuInfo,
          timeStamp,
          avaliable: result.data?.quantity?.quantity || 0,
        };
        await addAvaliable(data);
        return true;
      } catch (error) {
        toast.error(`${skuInfo}: 获取库存失败 ${(error as Error).message}`);
        return false;
      }
    },
    [addAvaliable],
  );

  useEffect(() => {
    refreshAvailableRender();
  }, []);

  return (
    <div {...props} className={cn(className, 'flex flex-col')}>
      <div className="absolute right-6 top-3 flex items-center z-10">
        <div
          className="mr-3 animate-spin"
          style={{
            opacity: isRefresh ? '1' : '0',
          }}
        >
          <LoaderCircle></LoaderCircle>
        </div>
        <Button
          onClick={async () => {
            await fetchAvailable();
            toast.success('完成所有的产品获取操作');
          }}
          size="sm"
          className="cursor-pointer hover:bg-[#337AB7] bg-[#428BCA] mr-3"
        >
          获取分类库存
        </Button>
        <Button
          onClick={async () => {
            const data = await getAvaliable();
            // console.log(data);
            const dataText = JSON.stringify(data);
            const fileName = categoryName + '-库存.json';
            toast.promise(saveFile(dataText, fileName), {
              loading: '正在导出库存中...',
              success: `成功导出库存到[${fileName}]文件中`,
              error: '导出失败',
            });
          }}
          size="sm"
          className="cursor-pointer mr-3"
        >
          导出库存
        </Button>
        <Button
          onClick={async () => {
            const fileHandle = await window.showOpenFilePicker();
            const loadingId = toast.loading('正在导入库存');
            try {
              const avaliableFile = await fileHandle[0].getFile();
              const avaliableJson = await avaliableFile.text();
              const avaliable = JSON.parse(avaliableJson) as GigaAvaliable[];
              await clearAvaliable();
              // await Promise.all(
              //   avaliable.map(async (item) => {
              //     await addAvaliable(item);
              //   }),
              // );
              setAvaliableImportTotal(avaliable.length);
              await concurrentLimit(
                avaliable.map((item) => {
                  return async () => {
                    await addAvaliable(item);
                    setAvaliableImportCount((prev) => prev + 1);
                  };
                }),
                1,
              );
              toast.success(`成功导入库存`);
              refreshAvailableRender();
              toast.dismiss(loadingId);
              setAvaliableImportTotal(0);
              setAvaliableImportCount(0);
            } catch (error) {
              toast.error(`导入库存失败 ${(error as Error).message}`);
              toast.dismiss(loadingId);
            }
          }}
          size="sm"
          className="cursor-pointer mr-3"
        >
          导入库存{avaliableImportTotal > 0 && `(${avaliableImportCount}/${avaliableImportTotal})`}
        </Button>
        <div className="">
          <RefreshCcw
            size={16}
            className="cursor-pointer transition-transform"
            style={{
              transform: isfreshing ? 'rotate(90deg)' : 'rotate(0deg)',
            }}
            onClick={async () => {
              if (isfreshing) {
                return;
              }
              setIsfreshing(true);
              await refreshAvailableRender().finally(() => {
                setIsfreshing(false);
              });
            }}
          ></RefreshCcw>
        </div>
      </div>
      <div className="grow relative flex flex-col">
        <AvaliableTable
          categoryName={categoryName}
          refreshAvailableRender={refreshAvailableRender}
          fetchAvaliableBySkuInfo={fetchAvaliableBySkuInfo}
          data={deferredTableData}
          timeStampKey={deferredTimeStampKey}
        ></AvaliableTable>
      </div>
    </div>
  );
}

export interface CustomReduction {
  start: string;
  end: string;
  id: string;
}

export interface LocalStorageData {
  pageSize: number;
  isFuzzleToDate: boolean;
}

const AvaliableTable = memo(function AvaliableTable({
  data,
  timeStampKey,
  refreshAvailableRender,
  fetchAvaliableBySkuInfo,
  categoryName,
}: {
  data: TableData[];
  timeStampKey: Set<number>;
  refreshAvailableRender: () => Promise<void>;
  fetchAvaliableBySkuInfo: (skuInfo: string, timeStamp?: number) => Promise<boolean>;
  categoryName: string;
}) {
  if (!categoryName) {
    return <div></div>;
  }
  // console.log('AvaliableTable render');
  const id = useId();
  const localStorageKey = 'pagination-avaliable';
  const [storageData, setStorageData] = useLocalStorage<LocalStorageData>(localStorageKey, {
    pageSize: 10,
    isFuzzleToDate: true,
  });
  const { getAvaliable, deleteAvaliable, clearAvaliable } = useAvaliableDB(categoryName);

  const [columnPinning, setColumnPinning] = useState<ColumnPinningState>({
    left: ['select', 'skuInfo', 'one-day-reduction'],
    right: ['actions'],
  });
  // console.log(storageDataString);
  const [sorting, setSorting] = useState<SortingState>(
    storageData.isFuzzleToDate
      ? [
          {
            id: 'one-day-reduction',
            desc: true,
          },
        ]
      : [],
  );
  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: storageData.pageSize,
  });
  const [rowSelection, setRowSelection] = useState({});
  const [deleteDataStringList, setDeleteDataStringList] = useState<string[]>([]);

  const [customReductionList, setCustomReductionList] = useState<CustomReduction[]>([]);
  const customReductionColumnIdPrefix = 'custom-reduction-';
  const timestampStartRef = useRef<HTMLSelectElement>(null);

  const timestampEndRef = useRef<HTMLSelectElement>(null);
  const headerHeight = 60;
  const cellHeight = 50;

  const [transformData, transformTimeStampList] = useMemo(() => {
    const timeStampKeyList = [...timeStampKey];
    timeStampKeyList.sort((a, b) => {
      return b - a;
    });
    // console.log(timeStampKeyList);
    const _transformTimeStampList: Set<string> = new Set();
    const _transformData = data.map((item) => {
      const newItem: TableData = {
        skuInfo: item.skuInfo,
      };
      timeStampKeyList.forEach((timeStamp) => {
        if (storageData.isFuzzleToDate) {
          const dataString = toDateString(timeStamp);
          if (!newItem[dataString] && newItem[dataString] !== 0) {
            newItem[dataString] = item[timeStamp] == undefined ? NaN : item[timeStamp];
          }
          _transformTimeStampList.add(dataString);
        } else {
          const dataString = new Date(timeStamp).toLocaleString();
          // newItem[dataString] = item[timeStamp] == undefined ? NaN : item[timeStamp];
          // if (item.skuInfo === 'B035P309787[gg]1025512' && dataString === '2025/5/14 07:41:35') {
          //   console.log(item.skuInfo, dataString, item, newItem, timeStamp);
          // }
          if (!newItem[dataString] && newItem[dataString] !== 0) {
            newItem[dataString] = item[timeStamp] == undefined ? NaN : item[timeStamp];
          }
          _transformTimeStampList.add(dataString);
        }
      });
      return newItem;
    });
    return [_transformData, [..._transformTimeStampList]];
  }, [data, timeStampKey, storageData.isFuzzleToDate]);

  const columns: ColumnDef<TableData>[] = useMemo(() => {
    const columns: ColumnDef<TableData>[] = [];
    columns.push({
      id: 'select',
      header: ({ table }) => (
        <Checkbox
          checked={
            table.getIsAllPageRowsSelected() ||
            (table.getIsSomePageRowsSelected() && 'indeterminate')
          }
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="Select all"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => row.toggleSelected(!!value)}
          aria-label="Select row"
        />
      ),
      enableSorting: false,
      enableHiding: false,
    });
    columns.push({
      id: 'skuInfo',
      accessorKey: 'skuInfo',
      header: () => <div className="text-center">货号</div>,
      cell: ({ row }) => {
        const skuInfo: string = row.getValue('skuInfo');
        return (
          <div
            onClick={() => {
              gotoGigaProductPage(skuInfo);
            }}
            className="text-left whitespace-nowrap cursor-pointer"
          >
            {skuInfo}
          </div>
        );
      },
    });
    if (storageData.isFuzzleToDate) {
      const id = 'one-day-reduction';
      columns.push({
        id,
        accessorFn: (row) => {
          const dataStringList = Object.keys(row)
            .filter((dataString) => {
              return dataString.match(/\d+\/\d+\/\d+/);
            })
            .sort((a, b) => {
              return new Date(b).getTime() - new Date(a).getTime();
            });
          if (dataStringList.length > 1) {
            const first = dataStringList[0];
            const second = dataStringList[1];
            const firstAvailable = +row[first];
            const secondAvailable = +row[second];
            return secondAvailable - firstAvailable;
          }
          return NaN;
        },
        header: () => <div className="text-center whitespace-nowrap">最新减少量</div>,
        cell: ({ row }) => {
          return (
            <div className="text-center">
              {Number.isNaN(row.getValue('one-day-reduction'))
                ? 'NaN'
                : row.getValue('one-day-reduction')}
            </div>
          );
        },
        sortUndefined: 'last',
        sortingFn: customReductionSortingFn(id),
      });
      customReductionList.map((customReduction) => {
        const id = customReductionColumnIdPrefix + customReduction.id;
        columns.push({
          id,
          accessorFn: (row) => {
            const firstAvailable = +row[customReduction.start];
            const secondAvailable = +row[customReduction.end];
            return secondAvailable - firstAvailable;
          },
          header: () => (
            <div className="text-center">{`${customReduction.start}~${customReduction.end}减少量`}</div>
          ),
          cell: ({ row }) => {
            return (
              <div className="text-center">
                {Number.isNaN(row.getValue(id)) ? 'NaN' : row.getValue(id)}
              </div>
            );
          },
          sortingFn: customReductionSortingFn(id),
        });
      });
    }
    columns.push(
      ...transformTimeStampList.map((timeStamp) => {
        return {
          id: `${timeStamp}`,
          accessorKey: `${timeStamp}`,
          header: () => (
            <div className="text-center">
              <div>{timeStamp}</div>
            </div>
          ),
          cell: ({ row }: { row: Row<TableData> }) => {
            return (
              <div className="text-left">
                {Number.isNaN(row.getValue(timeStamp + '')) ? 'NaN' : row.getValue(timeStamp + '')}
              </div>
            );
          },
          sortingFn: customReductionSortingFn(timeStamp),
        };
      }),
    );
    columns.push({
      id: 'actions',
      enableHiding: false,
      header() {
        return <div className="text-center">操作</div>;
      },
      cell: ({ row }) => {
        return (
          <div>
            <Button
              onClick={async () => {
                const skuInfo = row.getValue('skuInfo') as string;
                const isSuccess = await fetchAvaliableBySkuInfo(skuInfo);
                if (isSuccess) {
                  refreshAvailableRender();
                  toast.success(`${skuInfo}: 获取库存成功`);
                }
              }}
              size="sm"
              className="hover:bg-[#337AB7] bg-[#428BCA]"
            >
              获取库存
            </Button>
          </div>
        );
      },
    });
    return columns;
  }, [transformTimeStampList, storageData.isFuzzleToDate, customReductionList]);

  const table = useReactTable({
    data: transformData,
    columns,
    onSortingChange: setSorting,
    onColumnPinningChange: setColumnPinning,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    onPaginationChange: setPagination,
    onRowSelectionChange: setRowSelection,
    state: {
      sorting,
      rowSelection,
      columnPinning,
      pagination,
    },
  });

  return (
    <div className="flex flex-col grow">
      <div className="inline-flex items-center">
        <div className="inline-flex gap-2 items-center py-4">
          <Label className="whitespace-nowrap mb-0" htmlFor={id + 'page-size'}>
            分页页数:
          </Label>
          <Input
            value={storageData.pageSize}
            type="number"
            onChange={(event) => {
              const newPageSize = Number(event.target.value);
              setStorageData((prev) => {
                return { ...prev, pageSize: newPageSize };
              });
              setPagination({
                pageIndex: 0,
                pageSize: newPageSize,
              });
            }}
            id={id + 'page-size'}
            className="h-10 rounded-md border border-input px-3 py-2 w-16"
          />
        </div>
        <div className="inline-flex  px-3 gap-2 py-4 bd-bottom-gray items-center">
          <Checkbox
            checked={storageData.isFuzzleToDate}
            onCheckedChange={(state) => {
              const newIsFuzzleToDate = state ? true : false;
              setStorageData((prev) => {
                return { ...prev, isFuzzleToDate: newIsFuzzleToDate };
              });
            }}
            id={id + '-is-fuzzle-to-date'}
            className="rounded-[2px]"
          />
          <Label className="whitespace-nowrap mb-0" htmlFor={id + '-is-fuzzle-to-date'}>
            库存日期是否只精确到天数
          </Label>
        </div>
      </div>
      <div
        className="w-full grow relative flex flex-col"
        style={{
          opacity: transformData.length === 0 ? 0 : 1,
        }}
      >
        <div className="grow relative">
          <div className="rounded-sm !absolute h-full w-full overflow-auto">
            <div className="rounded-md border min-w-full inline-flex [&_thead]:sticky [&_thead]:top-[1px] [&_thead]:[box-shadow:0px_0px_0px_1px_#cfcfcf] [&_thead]:bg-[#f5f5f5]  [&_table]:!overflow-visible">
              <div className="sticky left-[0px] z-10 bg-white">
                <Table className="[&_td]:border [&_td]:border-input [&_th]:border [&_th]:border-input">
                  <TableHeader>
                    {table.getLeftHeaderGroups().map((headerGroup) => (
                      <TableRow key={headerGroup.id}>
                        {headerGroup.headers.map((header) => {
                          return (
                            <TableHead
                              key={header.id}
                              className="!p-2 relative"
                              style={{
                                height: headerHeight,
                              }}
                            >
                              {header.column.getCanSort() ? (
                                <div
                                  onClick={header.column.getToggleSortingHandler()}
                                  className="absolute cursor-pointer right-1 bottom-1"
                                  title={
                                    header.column.getCanSort()
                                      ? header.column.getNextSortingOrder() === 'asc'
                                        ? '升序'
                                        : header.column.getNextSortingOrder() === 'desc'
                                          ? '降序'
                                          : '默认排序'
                                      : undefined
                                  }
                                >
                                  <ArrowUpDown size={12}></ArrowUpDown>
                                </div>
                              ) : null}
                              {header.isPlaceholder
                                ? null
                                : flexRender(header.column.columnDef.header, header.getContext())}
                            </TableHead>
                          );
                        })}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {table.getRowModel().rows?.length ? (
                      table.getRowModel().rows?.map((row) => {
                        return (
                          <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
                            {row.getLeftVisibleCells().map((cell) => (
                              <TableCell
                                key={cell.id}
                                className=""
                                style={{
                                  height: cellHeight,
                                }}
                              >
                                {flexRender(cell.column.columnDef.cell, cell.getContext())}
                              </TableCell>
                            ))}
                          </TableRow>
                        );
                      })
                    ) : (
                      <TableRow>
                        <TableCell colSpan={columns.length} className="h-24 text-center">
                          No results.
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
              <div className="relative grow">
                <Table className="text-xs [&_td]:border [&_td]:border-input [&_th]:border [&_th]:border-input">
                  <TableHeader>
                    {table.getCenterHeaderGroups().map((headerGroup) => (
                      <TableRow key={headerGroup.id}>
                        {headerGroup.headers.map((header) => {
                          return (
                            <TableHead
                              key={header.id}
                              className="!p-2 relative"
                              style={{
                                height: headerHeight,
                              }}
                            >
                              {header.column.getCanSort() ? (
                                <div
                                  onClick={header.column.getToggleSortingHandler()}
                                  className="absolute cursor-pointer right-1 bottom-1"
                                  title={
                                    header.column.getCanSort()
                                      ? header.column.getNextSortingOrder() === 'asc'
                                        ? '升序'
                                        : header.column.getNextSortingOrder() === 'desc'
                                          ? '降序'
                                          : '默认排序'
                                      : undefined
                                  }
                                >
                                  <ArrowUpDown size={12}></ArrowUpDown>
                                </div>
                              ) : null}
                              {!header.column.id.startsWith(customReductionColumnIdPrefix) ? (
                                <div
                                  onClick={() => {
                                    const id = header.column.id.replace(
                                      customReductionColumnIdPrefix,
                                      '',
                                    );
                                    setCustomReductionList(
                                      customReductionList.filter((item) => item.id !== id),
                                    );
                                  }}
                                  className="absolute cursor-pointer right-1 top-[2px] text-[0]"
                                >
                                  <Checkbox
                                    checked={deleteDataStringList.includes(header.column.id)}
                                    onCheckedChange={(state) => {
                                      if (state ? true : false) {
                                        setDeleteDataStringList([
                                          ...deleteDataStringList,
                                          header.column.id,
                                        ]);
                                      } else {
                                        setDeleteDataStringList(
                                          deleteDataStringList.filter(
                                            (item) => item !== header.column.id,
                                          ),
                                        );
                                      }
                                    }}
                                    className="rounded-[2px] w-3 h-3 data-[state=checked]:text-destructive data-[state=checked]:bg-destructive border-destructive"
                                  />
                                </div>
                              ) : null}
                              {header.column.id.startsWith(customReductionColumnIdPrefix) ? (
                                <div
                                  onClick={() => {
                                    const id = header.column.id.replace(
                                      customReductionColumnIdPrefix,
                                      '',
                                    );
                                    setCustomReductionList(
                                      customReductionList.filter((item) => item.id !== id),
                                    );
                                  }}
                                  className="absolute cursor-pointer left-1 bottom-1"
                                >
                                  <Trash2 size={12} />
                                </div>
                              ) : null}
                              <div className="text-xs">
                                {header.isPlaceholder
                                  ? null
                                  : flexRender(header.column.columnDef.header, header.getContext())}
                              </div>
                            </TableHead>
                          );
                        })}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {table.getRowModel().rows?.length ? (
                      table.getRowModel().rows.map((row) => (
                        <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
                          {row.getCenterVisibleCells().map((cell) => (
                            <TableCell
                              key={cell.id}
                              className=""
                              style={{
                                height: cellHeight + 'px',
                              }}
                            >
                              {flexRender(cell.column.columnDef.cell, cell.getContext())}
                            </TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell colSpan={columns.length} className="h-24 text-center">
                          No results.
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
              <div className="bg-white sticky right-0">
                <Table className="[&_td]:border [&_td]:border-input [&_th]:border [&_th]:border-input">
                  <TableHeader>
                    {table.getRightHeaderGroups().map((headerGroup) => (
                      <TableRow key={headerGroup.id}>
                        {headerGroup.headers.map((header) => {
                          return (
                            <TableHead
                              key={header.id}
                              className="!p-2"
                              style={{
                                height: headerHeight,
                              }}
                            >
                              {header.isPlaceholder
                                ? null
                                : flexRender(header.column.columnDef.header, header.getContext())}
                            </TableHead>
                          );
                        })}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {table.getRowModel().rows?.length ? (
                      table.getRowModel().rows.map((row) => (
                        <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
                          {row.getRightVisibleCells().map((cell) => (
                            <TableCell
                              key={cell.id}
                              className=""
                              style={{
                                height: cellHeight + 'px',
                              }}
                            >
                              {flexRender(cell.column.columnDef.cell, cell.getContext())}
                            </TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell colSpan={columns.length} className="h-24 text-center">
                          No results.
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </div>
          </div>
        </div>
        <div className="mt-4">
          <Pagination>
            <PaginationContent>
              <PaginationItem>
                <PaginationPrevious
                  className="cursor-pointer select-none"
                  onClick={() => {
                    if (table.getCanPreviousPage()) {
                      table.previousPage();
                    }
                  }}
                />
              </PaginationItem>
              {table.getPageCount() > 0
                ? (() => {
                    const total = table.getPageCount();
                    const current = table.getState().pagination.pageIndex + 1;
                    const showPageCount = 3;
                    const showPageList = getPageList(total, current, showPageCount);
                    return showPageList.map((page) => {
                      return (
                        <PaginationItem key={page}>
                          {page === -Infinity || page === Infinity ? (
                            <PaginationEllipsis></PaginationEllipsis>
                          ) : (
                            <PaginationLink
                              className="cursor-pointer select-none"
                              isActive={current === page}
                              onClick={() => {
                                setPagination({
                                  pageIndex: page - 1,
                                  pageSize: storageData.pageSize,
                                });
                              }}
                            >
                              {page}
                            </PaginationLink>
                          )}
                        </PaginationItem>
                      );
                    });
                  })()
                : null}
              <PaginationItem>
                <PaginationNext
                  className="cursor-pointer select-none"
                  onClick={() => {
                    if (table.getCanNextPage()) {
                      table.nextPage();
                    }
                  }}
                />
              </PaginationItem>
              <div className="flex px-3 gap-2 items-center py-4">
                <Input
                  value={table.getState().pagination.pageIndex + 1}
                  type="number"
                  onChange={(event) => {
                    const page = event.target.value ? Number(event.target.value) : 1;
                    const total = table.getPageCount();
                    if (page > total) {
                      toast.info('总页数是 ' + total);
                    }
                    if (page < 1) {
                      toast.info('已经超出首页了');
                    }
                    setPagination({
                      pageIndex: page - 1,
                      pageSize: storageData.pageSize,
                    });
                  }}
                  className="h-10 rounded-md border border-input px-3 py-2 w-[70px]"
                />
              </div>
              <span>{`${table.getState().pagination.pageIndex + 1} of ${table.getPageCount()}  (${table.getPrePaginationRowModel().rows.length})`}</span>
            </PaginationContent>
          </Pagination>
        </div>
        <div className="flex items-center">
          <Button
            onClick={async () => {
              if (table.getIsSomeRowsSelected()) {
                const timeStamp = Date.now();
                await Promise.all(
                  table.getSelectedRowModel().rows.map(async (row) => {
                    // console.log('row', row.getValue('skuInfo'));
                    const skuInfo = row.getValue('skuInfo') as string;
                    const isSuccess = await fetchAvaliableBySkuInfo(skuInfo, timeStamp);
                    if (isSuccess) {
                      toast.success(`${skuInfo}: 获取库存成功`);
                    }
                  }),
                );
                refreshAvailableRender();
              } else {
                toast.error('请选择要批量处理的产品');
              }
            }}
            size="sm"
            className="hover:bg-[#337AB7] bg-[#428BCA] mr-3"
          >
            批量获取库存
          </Button>
          <Dialog>
            <DialogTrigger asChild>
              <Button
                onClick={async (event) => {
                  if (transformTimeStampList.length < 2 || !storageData.isFuzzleToDate) {
                    toast.error('没法选择两个时间段');
                    event.preventDefault();
                    return;
                  }
                }}
                size="sm"
                className="hover:bg-[#337AB7] bg-[#428BCA]"
              >
                检索不同时间段的减少量
              </Button>
            </DialogTrigger>
            <DialogContent className="sm:max-w-[425px] z-[1000002]">
              <DialogHeader>
                <DialogDescription>
                  减少量会使用结束日期的库存量减去开始日期的库存量
                </DialogDescription>
              </DialogHeader>
              <div className="grid gap-4 py-4">
                <div className="flex px-3 gap-2 items-center">
                  <Label className="whitespace-nowrap mb-0" htmlFor={id + '-timestamp-start'}>
                    开始:
                  </Label>
                  <Select defaultValue={transformTimeStampList[0]}>
                    <SelectTrigger id={id + '-timestamp-start'} className="w-[180px]">
                      <SelectValue ref={timestampStartRef} placeholder="选择开始日期" />
                    </SelectTrigger>
                    <SelectContent className="!z-[1000003]">
                      <SelectGroup>
                        {transformTimeStampList.map((dataString) => {
                          return (
                            <SelectItem key={dataString} value={dataString}>
                              {dataString}
                            </SelectItem>
                          );
                        })}
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex px-3 gap-2 items-center">
                  <Label className="whitespace-nowrap mb-0" htmlFor={id + '-timestamp-end'}>
                    结束:
                  </Label>
                  <Select defaultValue={transformTimeStampList[1]}>
                    <SelectTrigger id={id + '-timestamp-end'} className="w-[180px]">
                      <SelectValue ref={timestampEndRef} placeholder="选择结束日期" />
                    </SelectTrigger>
                    <SelectContent className="!z-[1000003]">
                      <SelectGroup>
                        {transformTimeStampList.map((dataString) => {
                          return (
                            <SelectItem key={dataString} value={dataString}>
                              {dataString}
                            </SelectItem>
                          );
                        })}
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <DialogFooter>
                <Button
                  onClick={() => {
                    const start =
                      timestampStartRef.current && timestampStartRef.current.textContent;
                    const end = timestampEndRef.current && timestampEndRef.current.textContent;
                    // console.log(start, end);
                    if (start && end) {
                      setCustomReductionList([
                        { start, end, id: generateRandomId() },
                        ...customReductionList,
                      ]);
                    }
                  }}
                  size={'sm'}
                >
                  添加
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
          <Button
            onClick={async () => {
              if (deleteDataStringList.length === 0) {
                toast.info('请先选择对应的列日期');
                return;
              }
              const gigaAvaliableList = await getAvaliable();
              const ids = gigaAvaliableList
                .filter((item) => {
                  let dataString = '';
                  if (storageData.isFuzzleToDate) {
                    dataString = toDateString(item.timeStamp);
                  } else {
                    dataString = new Date(item.timeStamp).toLocaleString();
                  }
                  return deleteDataStringList.includes(dataString);
                })
                .map((item) => {
                  return item.id;
                });
              await Promise.all(
                ids.map((id) => {
                  return deleteAvaliable(id);
                }),
              );
              toast.success(`删除 ${ids.length} 条数据成功`);
              refreshAvailableRender();
            }}
            size="sm"
            className="hover:bg-destructive bg-destructive ml-auto mr-3"
          >
            删除选择的日期数据
          </Button>
          <Button
            onClick={async () => {
              await clearAvaliable();
              toast.success(`清除所有的数据成功`);
              refreshAvailableRender();
            }}
            size="sm"
            className="hover:bg-destructive bg-destructive"
          >
            清除所有的数据
          </Button>
        </div>
      </div>
    </div>
  );
});
